package com.gitee.cui.basic.create;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 第三种创建现成的方式，通过Callable接口和FutureTask类相结合创建线程。
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/9 17:21
 **/
@Slf4j
public class CreateThread3 {

    private static final int COMPUTE_TIMES = 100000000;

    static class ReturnedTask implements Callable<Long> {

        @Override
        public Long call() throws Exception {
            log.info("{} 线程开始运行", ThreadUtil.getCurThreadName());
            long start = System.currentTimeMillis();
            Thread.sleep(1000);
            // 模拟一个耗时的操作
            for (int i = 0; i < COMPUTE_TIMES; i++) {
                long j = i * 10000;
            }
            long end = System.currentTimeMillis();
            log.info("{} 线程运行结束", ThreadUtil.getCurThreadName());
            return end - start;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReturnedTask returnedTask = new ReturnedTask();
        FutureTask<Long> futureTask = new FutureTask<>(returnedTask);
        Thread thread = new Thread(futureTask, "returnedThread");
        thread.start();
        Thread.sleep(500);
        log.info("{} 让子弹飞一会", ThreadUtil.getCurThreadName());
        log.info("{} 做一些自己的事情", ThreadUtil.getCurThreadName());
        // 模拟一个耗时的操作
        for (int i = 0; i < COMPUTE_TIMES / 2; i++) {
            long j = i * 10000;
        }
        log.info("{} 获取并发任务的执行结果", ThreadUtil.getCurThreadName());
        try {
            log.info(thread.getName() + " 线程占用时间：{}", futureTask.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        log.info("{} 线程运行结束", ThreadUtil.getCurThreadName());
    }
}
